<script setup lang="ts">
import {onMounted, onUnmounted, ref, type Ref, shallowRef} from 'vue';
import {BoxGeometry, DirectionalLight, Mesh, MeshStandardMaterial, Scene} from 'three';
import RendererHelper from '@/core/helpers/RendererHelper';
import PerspectiveCameraHelper from '@/core/helpers/PerspectiveCameraHelper';

const el = shallowRef() as Ref<HTMLDivElement>;
let rendererHelper: RendererHelper;
let perspectiveCameraHelper: PerspectiveCameraHelper;
const rotateX = ref(true);
const rotateY = ref(true);
const rotateZ = ref(false);

onMounted(() => {
  rendererHelper = new RendererHelper(el.value);
  const renderer = rendererHelper.renderer;
  perspectiveCameraHelper = new PerspectiveCameraHelper(renderer.domElement);
  const camera = perspectiveCameraHelper.camera;
  camera.position.set(0, 0, 4);

  const scene = new Scene();
  const geometry = new BoxGeometry(1, 1, 1);
  const material = new MeshStandardMaterial({color: 0xff0000});
  const cube = new Mesh(geometry, material);
  scene.add(cube);
  const light = new DirectionalLight();
  light.position.set(-2, 2, 4);
  scene.add(light);

  function animate() {
    if (rotateX.value)
      cube.rotation.x += 0.005;
    if (rotateY.value)
      cube.rotation.y += 0.005;
    if (rotateZ.value)
      cube.rotation.z += 0.005;
    renderer.render(scene, camera);
  }

  renderer.setAnimationLoop(animate);
});

onUnmounted(() => {
  rendererHelper.dispose();
  perspectiveCameraHelper.dispose();
});
</script>

<template>
  <div class="height100 ls-abs-outer">
    <div class="height100" ref="el">
    </div>
  </div>
  <div class="controlBox">
    <div>
      绕X轴旋转
      <el-switch v-model="rotateX"></el-switch>
    </div>
    <div>
      绕Y轴旋转
      <el-switch v-model="rotateY"></el-switch>
    </div>
    <div>
      绕Z轴旋转
      <el-switch v-model="rotateZ"></el-switch>
    </div>
  </div>
</template>

<style scoped>

</style>
